package com.collabscm.pf.persistence;

import java.util.Map;

import com.collabscm.pf.BaseObject;
import com.collabscm.pf.logging.Logger;
import com.collabscm.pf.logging.LoggerFactory;

/**
 * 动态查询对象
 *
 * @author Zeng Raoxing
 */
public class DynamicQuery extends BaseObject {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(DynamicQuery.class);
	public static final String select = "select";
	public static final String from = "from";
	public static final String where = "where";
	public static final String and = "and";
	public static final String or = "or";
	public static final String orderBy = "order by";
	/**升序*/
	public static final String asc = " asc";
	/**降序*/
	public static final String desc = " desc";
	/**
	 * 查询语句
	 */
	private String queryStatement;
	/**
	 * 查询总数的语句
	 */
	private String countStatement;
	/**
	 * 是否是本地查询
	 */
	private boolean isNative;
	/**
	 * 过滤的参数
	 */
	private Map<String, Object> filters;
	
	public boolean isNative() {
		return isNative;
	}
	public void setNative(boolean isNative) {
		this.isNative = isNative;
	}
	public Map<String, Object> getFilters() {
		return filters;
	}
	public void setFilters(Map<String, Object> filters) {
		this.filters = filters;
	}
	public String getQueryStatement() {
		return queryStatement;
	}
	public void setQueryStatement(String queryStatement) {
		this.queryStatement = queryStatement;
	}
	/**
	 * 得到查询总数的语句，如果已定义了那么直接返回，否则自动根据查询语句生成查总数的语句。
	 * @return
	 */
	public String getCountStatement() {
		if(countStatement == null && queryStatement != null) {
			int formPos = queryStatement.indexOf(from);
			if(formPos > 0) {
				//生成新的查询语句。
				countStatement = "select count(*) " + queryStatement.substring(formPos);
				logger.debug("自动生成的查总数的语句为{}。", countStatement);
			} else {
				logger.error("无法生成查询总数的语句，原因：查询语句{}定义中未定义from或from的大小写不匹配。", queryStatement);
			}
		}
		return countStatement;
	}
	public void setCountStatement(String countStatement) {
		this.countStatement = countStatement;
	}

}
